const Koa = require('koa');
const fs = require('fs');
const Router = require('koa-router');
const thrift = require('thrift');
const TicketService = require('../thrift/TicketService.js'); // ticket.thrift文件 服务定义
const ttypes = require('../thrift/ticket_types.js'); // ticket.thrift文件 结构定义
const assert = require('assert');


const app = new Koa();
let home = new Router();

// 固定格式
var transport = thrift.TBufferedTransport;
var protocol = thrift.TBinaryProtocol;

var connection = thrift.createConnection("192.168.6.9", 9090, {
  transport : transport,
  protocol : protocol
});

connection.on('error', function(err) {
  assert(false, err);
});
// 固定格式 end

// Create a Calculator client with the connection
var client = thrift.createClient(TicketService, connection);



function render(page) {
    return new Promise((resolve, reject) => {
        let viewUrl = `../web/${page}`
        fs.readFile(viewUrl, "binary", (err, data) => {
            if (err) {
                reject(err)
            } else {
                resolve(data)
            }
        })
    })
}


home.get('/', async (ctx) => {
    let html = await render("index.html")
    ctx.body = html;
});

home.get('/404', async (ctx) => {
    ctx.body = '404 page!'
}).get('/getTicketList', async (ctx) => {
    // console.log('00000', client) 
    var data = await new Promise((resolve, reject) => {
        client.listTicket(function(err, response) {
            console.log('....', response);
            response.forEach(element => {
                element.pay = element.premote * element.price;
            });
            resolve(response);
        });
    })

    console.log('dddddd', data);
    // data = [ 
    //     new ttypes.Ticket({'id': 1}) // mock
    // ];
    ctx.body = {
        "status": "200",
        data
    }
}).get('/search', async (ctx) => {
    const id = ctx.query.id;
    const ticket = new ttypes.Ticket({id});
    // ticket.id = id;
    var data = await new Promise((resolve, reject) => {
        client.getTicket(ticket, function(err, response) {
            // console.log('....', response);
            resolve(response);
        });
    })

    console.log('dddddd==', data);
    let status = '存在票';
    if(data.code != 0){
        status = "不存在票"
    }
    // data = [ 
    //     new ttypes.Ticket({'id': 1}) // mock
    // ];
    ctx.body = {
        "status": status,
        data
    }
})




// 加载路由中间件
app.use(home.routes()).use(home.allowedMethods())



app.listen(3000)
console.log('[demo] start-quick is starting at port 3000')
